<?php

namespace app\admin\controller;

use think\exception\FuncNotFoundException;
use think\exception\ValidateException;
use app\model\UsersSessions;

class Base extends \app\BaseController
{

	protected $userInfo = []; //token解码的用户信息

	protected function initialize()
	{
		$controller = $this->request->controller();
		$action = $this->request->action();
		$app = app('http')->getName();

		$url =  "{$app}/{$controller}/{$action}";

		if (!in_array($url, config('my.nocheck'))) {
			$this->checkTokenAuth();
		}
	}


	//设置token
	protected function setToken($data)
	{

		$data =	serialize($data);
		$token = md5(uniqid());

		//登录的时候把token写入数据表
		$tokenInfo = UsersSessions::where('token', $token)->find();
		if (!$tokenInfo) {
			UsersSessions::create([
				'token' => $token,
				'ptype' => 'pc',
				'ip' => getRealIP(),
				'expire_time' => time(),
				'data' => $data,
				'status'=>1
			]);
		}

		return $token;
	}

	//检测token
	protected function checkTokenAuth()
	{
		$token = $this->request->header('Authorization');
		if (!$token) {
			abort(101, 'token不能为空');
		}

		$tokenInfo = UsersSessions::where('token', $token)->find()->toArray();

		if (!$tokenInfo['status']) {
			abort(101, '状态被禁用');
		}

		if (!$tokenInfo['dev_status']) {
			abort(101, '你已下线,账户在其它设备登录!');
		}

		if (!$tokenInfo) {
			abort(101, 'token不存在');
		}

		if (($tokenInfo['expire_time'] - config('my.token_expire_time')) > time()) {
			abort(101, '登录状态已过期，请重新登录');
		}

		$this->userInfo = iunserializer($tokenInfo['data']);
		
		event('DoLog', $this->userInfo['username']);	//写入操作日志
	}

	//验证器 并且抛出异常
	protected function validate($data, $validate)
	{
		try {
			validate($validate)->scene($this->request->action())->check($data);
		} catch (ValidateException $e) {
			throw new ValidateException($e->getError());
		}
		return true;
	}

	//获取所有菜单
	protected function getTotalMenus()
	{
		$menu =  $this->getBaseMenus();
		$order_array = array_column($menu, 'sort');	 //数组排序
		array_multisort($order_array, SORT_ASC, $menu);

		return $menu;
	}


	//返回当前应用的菜单列表
	protected function getBaseMenus()
	{
		$field = 'id,pid,title,status,icon,sort,path,component_path';
		$list = \app\model\AdminMenu::field($field)
			->where(['status' => 1, 'type' => 1])
			->order('sort asc')
			->select()
			->toArray();
		if ($list) {
			foreach ($list as $key => $val) {
				$menus[$key]['name'] = $val['path'];
				$menus[$key]['pid'] = $val['pid'];
				$menus[$key]['id'] = $val['id'];
				$menus[$key]['title'] = $val['title'];
				$menus[$key]['sort'] = $val['sort'];
				$menus[$key]['icon'] = $val['icon'] ? $val['icon'] : 'el-icon-menu';
				$menus[$key]['path'] = $val['path'];
				$menus[$key]['component_path'] = $val['component_path'];
			}
			return _generateListTree($menus, 0, ['id', 'pid']);
		}
	}

	//获取要加载的组件
	protected function getComponents($menu)
	{
		$components = [];
		foreach ($menu as $v) {
			$components[] = [
				'name' => $v['name'],
				'path' => $v['path'],
				'meta' => ['title' => $v['title']],
				'component_path' => $v['component_path']
			];
			if ($v['children']) {
				$components = array_merge($components, $this->getComponents($v['children']));
			}
		}
		return $components;
	}


	public function __call($method, $args)
	{
		throw new FuncNotFoundException('方法不存在', $method);
	}
}
